import 'dart:ui';

extension ColorExt on Color {
  /// 从16进制字符串获取颜色
  /// 支持格式: #aabbcc, aabbcc, #ffaabbcc, ffaabbcc
  /// 转换失败时返回null
  static Color? fromHex(String hexString) => colorFromHex(hexString);
}

/// 从16进制字符串获取颜色
/// 支持格式: #aabbcc, aabbcc, #ffaabbcc, ffaabbcc
/// 转换失败时返回null
Color? colorFromHex(String hexString) {
  final buffer = StringBuffer();
  if (hexString.length == 6 || hexString.length == 7) {
    buffer.write('ff');
  }
  buffer.write(hexString.replaceFirst('#', ''));
  try {
    return Color(int.parse(buffer.toString(), radix: 16));
  } catch (e) {
    return null;
  }
}
